#include "suggestionwidget.h"
#include "ui_suggestionwidget.h"
#include "databasemanager.h"
#include "suggest.h"
#include <QSqlQueryModel>
#include <QSqlError>
#include <QDebug>
#include <QMessageBox>

suggestionwidget::suggestionwidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::suggestionwidget)
{
    ui->setupUi(this);
    loadRecommendations();

    // 按钮点击信号连接
    connect(ui->pushButtonAdd, &QPushButton::clicked, this, &suggestionwidget::on_pushButtonAdd_clicked);
}

suggestionwidget::~suggestionwidget()
{
    delete ui;
}

void suggestionwidget::loadRecommendations()
{
    QSqlQueryModel *model = new QSqlQueryModel(this);
    QString sql = R"(
        SELECT r.recommendation_id AS 推荐编号,
               v.name AS 场馆名称,
               r.suggestion AS 推荐理由,
               r.strategy AS 游玩攻略,
               r.created_at AS 推荐时间
        FROM Venue_Recommendations r
        JOIN Venues v ON r.venue_id = v.venue_id
        ORDER BY r.created_at DESC;
    )";
    model->setQuery(sql, DatabaseManager::instance().getDatabase());

    if (model->lastError().isValid()) {
        qDebug() << "加载推荐失败:" << model->lastError().text();
        QMessageBox::warning(this, "错误", "加载推荐信息失败！");
        return;
    }

    ui->tableView->setModel(model);
    ui->tableView->resizeColumnsToContents();
}

void suggestionwidget::on_pushButtonAdd_clicked()
{
    suggest *suggestPage = new suggest;
    suggestPage->setAttribute(Qt::WA_DeleteOnClose);
    suggestPage->show();  // 独立窗口展示推荐填写页面
}

void suggestionwidget::on_pushButtonRefresh_clicked()
{
    loadRecommendations();
    QMessageBox::information(this, "刷新成功", "推荐信息已更新！");
}
